﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace TCPlib.OML
{
    public class BasicClass
    {
        internal static TcpClient Client;     // 连接
        internal static NetworkStream Stream; //本机PC的节点号
        internal static byte pcNode, plcNode; //PLC的节点号

        /// <summary>
        /// 检查PLc的连接状态
        /// </summary>
        /// <param name="ip">PLC的Ip</param>
        /// <param name="timeOut">超时时间</param>
        /// <returns></returns>
        internal static bool PingCheck(string ip, int timeOut)
        {
            Ping ping = new Ping();
            PingReply pr = ping.Send(ip, timeOut);
            if (pr.Status == IPStatus.Success)
                return true;
            else
                return false;
        }

        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="sd"></param>
        /// <returns></returns>
        internal static short SendData(byte[] sd)
        {
            try
            {
                Stream.Write(sd, 0, sd.Length);
                return 0;
            }
            catch
            {
                return -1;
            }
        }

        /// <summary>
        /// 接收数据
        /// </summary>
        /// <param name="rd"></param>
        /// <returns></returns>
        internal static short ReceiveData(byte[] rd)
        {
            try
            {
                int index = 0;
                do
                {
                    int len = Stream.Read(rd, index, rd.Length - index);
                    if (len == 0)
                        return -1;//这里控制读取不到数据时就跳出,网络异常断开，数据读取不完整。
                    else
                        index += len;
                } while (index < rd.Length);
                return 0;
            }
            catch
            {
                return -1;
            }
        }




    }
}
